package com.secneo.appshare.activities;

import java.io.ByteArrayOutputStream;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.secneo.appshare.R;
import com.secneo.appshare.api.LocalStore;
import com.secneo.appshare.api.impl.RemoteApiImpl;
import com.secneo.appshare.common.ActivityUtil;
import com.secneo.appshare.common.Constants;

public class PopAlarmActivity extends Activity
{
	private AlertDialog dialog = null;
	ImageView likeAppImageView, sendAppImageView, shareAppImageView, hideAppImageView, uninstallAppImageView, lunchAppImageView, tintAppImageView;
	OnClickListener likeAppImageViewListener, sendAppImageViewListener, shareAppImageViewListener, hideAppImageViewListener, uninstallAppImageViewListener, lunchAppImageViewListener,
			tintAppImageViewListener;
	private String packName = "";
	private String applicationName = "";
	private String app_icon_url = "";
	private int dialogType;
	JSONObject js = null;
	private byte[] bitmapdata = null;
	public final int MSG_INIT_OK = 1;
	public final int MSG_INIT_ERROR = 2;
	public final int MSG_INIT_DROP=3;
	private ProgressDialog mNetProgressBar = null;
	Handler handler = new Handler()
	{

		@Override
		public void handleMessage(Message msg)
		{

			switch (msg.what)
			{
				case MSG_INIT_OK:
					if (mNetProgressBar != null) 
					{
						mNetProgressBar.dismiss();
						mNetProgressBar = null; 
					}
					ActivityUtil.showToast(PopAlarmActivity.this, PopAlarmActivity.this.getResources().getText(R.string.pinglun_title).toString(), PopAlarmActivity.this.getResources().getText(
							R.string.pinglun_sucess).toString());
					
//					ApplicationInfoActivity.from_activity = 1;
					
					finish();
					dialog.dismiss();
					
					break;

				case MSG_INIT_ERROR:
					if (mNetProgressBar != null) 
					{
						mNetProgressBar.dismiss();
						mNetProgressBar = null; 
					}
					Toast.makeText(PopAlarmActivity.this, R.string.word_remark_is_error, 2000).show();
					break;
					
				case Constants.MSG_ACTION_MSG_OK:
					if (mNetProgressBar != null) 
					{
						mNetProgressBar.dismiss();
						mNetProgressBar = null; 
					}
					finish();
					dialog.dismiss();
					Toast.makeText(PopAlarmActivity.this, R.string.msg_ok, 2000).show();
					break;
				case Constants.MSG_ACTION_MSG_ERROR:
					if (mNetProgressBar != null) 
					{
						mNetProgressBar.dismiss();
						mNetProgressBar = null; 
					}
					Toast.makeText(PopAlarmActivity.this, R.string.msg_error, 2000).show();
					break;
				case MSG_INIT_DROP:
					if (mNetProgressBar != null) 
					{
						mNetProgressBar.dismiss();
						mNetProgressBar = null; 
					}
					Toast.makeText(PopAlarmActivity.this, "今日频率太高，明天再试吧", 2000).show();
					break;
					
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		Bundle bundle = getIntent().getExtras();
		// 软件包名
		packName = bundle.getString("package_name");
		applicationName = bundle.getString("app_name");
		dialogType = bundle.getInt("type");
		app_icon_url = bundle.getString("appIconUrl");
		
		dialog = new AlertDialog.Builder(PopAlarmActivity.this).create();
		LayoutInflater inflater = LayoutInflater.from(PopAlarmActivity.this);
		View backupExpandHeader = inflater.inflate(R.layout.appshare_remark_dialog, null);

		dialog.setView(backupExpandHeader);
		dialog.setCancelable(true);
		dialog.show();
		dialog.setOnCancelListener(new OnCancelListener()
		{

			@Override
			public void onCancel(DialogInterface dialog)
			{
				// TODO Auto-generated method stub
				dialog.dismiss();
				finish();
			}
		});
		ImageView iconImageView = (ImageView) backupExpandHeader.findViewById(R.id.AppIconImageView);
		TextView appNameTextView = (TextView) backupExpandHeader.findViewById(R.id.AppNameTextView);
		TextView appNameTitleImageView = (TextView) backupExpandHeader.findViewById(R.id.AppNameTitleTextView);
		final EditText remarkEditText = (EditText) backupExpandHeader.findViewById(R.id.RemarkEditText);
		Button okButton = (Button) backupExpandHeader.findViewById(R.id.RemarkOkButton);
		Button cancelButton = (Button) backupExpandHeader.findViewById(R.id.RemarkCancelButton);

		if(dialogType == 0)
		{
			Drawable icon = null;// 图片
			String appName = null;// 程序名称
			String packageName = null;
			PackageManager manager = this.getPackageManager();
			try
			{
				PackageInfo info = manager.getPackageInfo(packName, 0);// this.getPackageName()这个是程序包名
				packageName = info.packageName;
				appName = info.applicationInfo.loadLabel(getPackageManager()).toString();
	
				icon = info.applicationInfo.loadIcon(getPackageManager());
	
			} catch (NameNotFoundException e)
			{
				// TODO Auto-generated catch block
				appName = applicationName;
			}
	
			if (icon != null)
			{
				iconImageView.setVisibility(View.VISIBLE);
				iconImageView.setImageDrawable(icon);
				Bitmap bitmap = ((BitmapDrawable) icon).getBitmap();
				ByteArrayOutputStream stream = new ByteArrayOutputStream();
				bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
				bitmapdata = stream.toByteArray();
			}
			else
			{
				iconImageView.setVisibility(View.GONE);
			}
			appNameTextView.setText(appName);
			appNameTitleImageView.setText(this.getResources().getString(R.string.word_remark_title, appName));
		}
		else
		{
			iconImageView.setVisibility(View.GONE);
			appNameTextView.setVisibility(View.GONE);
			appNameTitleImageView.setText(this.getResources().getString(R.string.word_msg_title, applicationName));
		}

		okButton.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				String remarkContent = remarkEditText.getText().toString().trim();
				if (remarkContent.length() == 0)
				{
					if(dialogType == 0)
						Toast.makeText(PopAlarmActivity.this, R.string.word_remark_error, 2000).show();
					else
						Toast.makeText(PopAlarmActivity.this, R.string.word_msg_error, 2000).show();
				}
				else if(remarkContent.length() > 33 && (dialogType != 0))
				{
					Toast.makeText(PopAlarmActivity.this, "输入字数超过了上限（33个中文）！", 2000).show();
				}
				else
				{
					String note = "";
					if(dialogType == 0)
						note = "发送评论中...";
					else
						note = "私信正在发送中...";
					mNetProgressBar = ProgressDialog.show(PopAlarmActivity.this, null, note ,true);
					Thread sendRemark = new Thread(new Runnable()
					{
						@Override
						public void run()
						{
							String remarkContent = remarkEditText.getText().toString().trim();
							RemoteApiImpl rai = new RemoteApiImpl();
							String uid = LocalStore.getLocaleStoreInstance(PopAlarmActivity.this).getUid();
							
							if(dialogType == 0)
							{
								js=rai.getUserAction(PopAlarmActivity.this, uid, remarkContent, packName,"3");
								String status="";
								try {
									status = js.getString("status");
								} catch (Exception e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								if (js != null)
								{
									if("ok".equals(status))
									{
										handler.sendEmptyMessage(MSG_INIT_OK);
									}else if("drop".equals(status))
									{
										handler.sendEmptyMessage(MSG_INIT_DROP);
									}
								}
								else
									handler.sendEmptyMessage(MSG_INIT_ERROR);
								
								ActivityUtil.shareToWeibo(PopAlarmActivity.this, Constants.UPLOAD_ACTION_TALK, applicationName, remarkContent, bitmapdata, null, 
										app_icon_url, null, packName);

								if(!Constants.SWITCH_SINA_CUSTOM){
									if(bitmapdata != null){
										rai.share2QWeiboMsg(PopAlarmActivity.this, Constants.UPLOAD_ACTION_TALK, 
												applicationName + ":" + remarkContent,  bitmapdata, null, null, packName) ;
									} else {
										rai.share2QWeiboMsg(PopAlarmActivity.this, Constants.UPLOAD_ACTION_TALK, 
												applicationName + ":" + remarkContent, null, null, packName) ;
									}
								}
								
							}
							else
							{
								int ret = rai.sendMsg(uid, packName, remarkContent);
								if(ret > 0)
								{
									Message msg = new Message();
									msg.what = Constants.MSG_ACTION_MSG_OK;
									handler.sendMessage(msg);
								}
								else
								{
									Message msg = new Message();
									msg.what = Constants.MSG_ACTION_MSG_ERROR;
									handler.sendMessage(msg);
								}
							}
						}
					});
					sendRemark.start();
				}
			}
		});
		cancelButton.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				finish();
				dialog.dismiss();
			}
		});

	}

	public static boolean show(Activity activity, String packagename, String appName, int type, String appIconUrl)
	{
		Intent intent = new Intent(activity, PopAlarmActivity.class);
		Bundle mBundle = new Bundle();
		mBundle.putString("package_name", packagename);
		mBundle.putString("app_name", appName);
		mBundle.putInt("type", type);
		mBundle.putString("appIconUrl", appIconUrl);
		intent.putExtras(mBundle);
		activity.startActivityForResult(intent, 1);

		return true;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK)
		{
			dialog.dismiss();
			finish();
			return true;

		} else
		{
			return super.onKeyDown(keyCode, event);
		}

	}

}
